package cn.aitstone.system.service.impl;

import cn.aitstone.org.domain.Department;
import cn.aitstone.system.domain.Menu;
import cn.aitstone.system.mapper.MenuMapper;
import cn.aitstone.system.service.IMenuService;
import cn.aitstone.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sheldon
 * @since 2022-07-11
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        List<Menu> menuAll = menuMapper.loadAll();
        ArrayList<Menu> menuTree = new ArrayList<>();
        HashMap<Long, Menu> menuMap = new HashMap<>();
        for (Menu menu : menuAll){
            menuMap.put(menu.getId(), menu);
        }
        for (Menu menuTemp : menuAll){
            if(menuTemp.getParentId() == null){
                menuTree.add(menuTemp);
            } else {
                // 从map集合中获取到父对象，将自己添加到父对象的children集合中
                Menu menu = menuMap.get(menuTemp.getParentId());
                if (menu != null){
                    menu.getChildren().add(menuTemp);
                }
            }

        }
        return menuTree;

    }
}
